<template>
  <div class="index-page">
    <!-- 控制菜单 -->
    <button size="mini" @click="tapAt">@艾特</button>
    <button size="mini" @click="tapInsertText">插入🥹</button>
    <button size="mini" @click="tapInsertHtml">插入富文本</button>
    <button size="mini" @click="tapReadOnly">可写 {{ isEditable }}</button>
    <button size="mini" @click="logAt">打印艾特</button>
    <button size="mini" @click="logLastContent">打印最新内容</button>
    <button size="mini" @click="changeHtml">初始化内容</button>
    <button size="mini" @click="backspace">退格</button>
    <button size="mini" @click="skipWeb">跳转webview</button>

    <!-- 输入框 -->
    <sv-input-at
      ref="atInputRef"
      v-model:html="htmlContent"
      :editable="isEditable"
      max-height="80px"
      max-length="100"
      @input="onInput"
      @at="onAt"
      @atLink="onAtLink"
      @overmax="onOvermax"
    ></sv-input-at>

    <!-- 弹窗 -->
    <div class="at-panel" v-if="showAtPanel">
      <input type="text" style="border: 1px solid #ccc" placeholder="请输入" />
      <div
        class="at-panel-item"
        :class="[toAtList.includes(item) ? 'at-active' : '']"
        v-for="item in atList"
        :key="item.id"
        @click="selectAt(item)"
      >
        {{ item.name }}
      </div>
      <div style="display: flex">
        <button type="warn" size="mini" @click="showAtPanel = !showAtPanel">关闭</button>
        <button type="primary" size="mini" @click="confirmAt">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'

const atInputRef = ref()

const isEditable = ref(true)

// 通过双向绑定来初始化内容，会导致光标聚焦，开启只读则不会聚焦
const htmlContent = ref(`&nbsp;<span
    data-user="{&quot;name&quot;:&quot;熊大&quot;,&quot;id&quot;:1}"
    class="at-link"
    contenteditable="false"
    style="display: inline-block; color: blue;"
    >@熊大</span>&nbsp;123 <a href="https://www.baidu.com">百度</a>`)

onMounted(() => {
  // 通过initContent初始化内容，不会导致光标聚焦
  // atInputRef.value.initContent(``)
})

const showAtPanel = ref(false)
const atList = ref([
  {
    name: '熊大',
    id: 1
  },
  {
    name: '熊二',
    id: 2
  },
  {
    name: '张三',
    id: 3
  },
  {
    name: '李四',
    id: 4
  },
  {
    name: '王五',
    id: 5
  }
])

function onInput(e) {
  console.log('onInput', e)
}

function tapAt() {
  onAt()
}

function tapInsertText() {
  // 消除键盘影响，软键盘不弹出
  atInputRef.value.noKeyboardEffect(() => {
    atInputRef.value.insertText(`🥹`)
  })
}

function tapInsertHtml() {
  atInputRef.value.noKeyboardEffect(() => {
    atInputRef.value.insertHtml(
      `<img style="width:16px;height:16px" src="https://img.yzcdn.cn/vant/cat.jpeg" />`
    )
  })
}

function tapReadOnly() {
  isEditable.value = !isEditable.value
}

function onAt() {
  atInputRef.value.blur()
  toAtList.value = []
  showAtPanel.value = true
}

const toAtList = ref([])
function selectAt(e) {
  // console.log('selectAt', e)
  if (!toAtList.value.includes(e)) {
    // 添加
    toAtList.value.push(e)
  } else {
    // 移除
    toAtList.value = toAtList.value.filter((item) => item.id !== e.id)
  }
}

async function confirmAt() {
  console.log('confirmAt ===> ', toAtList.value)
  atInputRef.value.insertAts(toAtList.value)

  // for (let i = 0; i < toAtList.value.length; i++) {
  //   const user = toAtList.value[i]
  //   atInputRef.value.insertAt(user)

  //   await new Promise((resolve) => {
  //     setTimeout(() => {
  //       resolve()
  //     }, 100)
  //   })
  // }

  showAtPanel.value = false
}

function onAtLink(e) {
  uni.showToast({
    title: `点击了 ${e.name}`,
    icon: 'none'
  })
  console.log(`点击了 ${e.name}`)
}

function onOvermax() {
  console.log('超过最大字数限制')
}

function logAt() {
  console.log('艾特数组（去重）', atInputRef.value.getAllAtLink())
}

function logLastContent() {
  console.log('最新内容', htmlContent.value)
}

function changeHtml() {
  htmlContent.value = `新的初始化内容&nbsp;<span
      data-user="{&quot;name&quot;:&quot;张三&quot;,&quot;id&quot;:3}"
      class="at-link"
      contenteditable="false"
      style="display: inline-block; color: blue;"
    >@张三</span>&nbsp;新的初始化内容`
}

function backspace() {
  atInputRef.value.backspace()
}

function skipWeb() {
  uni.navigateTo({
    url: '/pages/web/web'
  })
}
</script>

<style lang="scss">
.index-page {
  padding: 20px;
  box-sizing: border-box;

  .at-panel {
    width: 300px;
    position: absolute;
    top: 50%;
    left: 50%;
    background-color: #fff;
    transform: translate(-50%, -50%);
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.5);
    margin-top: 20px;
    border-radius: 4px;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;

    .at-panel-item {
      border: 1px dashed #0000ff;

      &.at-active {
        border: 2px solid #66ccff;
      }
    }
  }
}
</style>
